package com.school.controller;

import com.school.common.PageResult;
import com.school.common.Result;
import com.school.entity.Student;
import com.school.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;

/**
 * 学生信息控制器
 * 
 * @author School Development Team
 * @version 1.0.0
 * @since 2024
 */
@Tag(name = "学生管理", description = "学生信息管理相关接口")
@RestController
@RequestMapping("/students")
@Validated
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Operation(summary = "分页查询学生信息", description = "根据条件分页查询学生信息列表")
    @GetMapping("/page")
    public Result<PageResult<Student>> getStudentPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "学生姓名") @RequestParam(required = false) String name,
            @Parameter(description = "班级ID") @RequestParam(required = false) String classId,
            @Parameter(description = "学生状态") @RequestParam(required = false) String status,
            @Parameter(description = "年级") @RequestParam(required = false) Integer gradeLevel,
            @Parameter(description = "性别") @RequestParam(required = false) String gender,
            @Parameter(description = "关键词搜索") @RequestParam(required = false) String keyword) {
        
        Map<String, Object> params = Map.of(
            "name", name != null ? name : "",
            "classId", classId != null ? classId : "",
            "status", status != null ? status : "",
            "gradeLevel", gradeLevel != null ? gradeLevel : "",
            "gender", gender != null ? gender : "",
            "keyword", keyword != null ? keyword : ""
        );
        
        PageResult<Student> result = studentService.getStudentPage(current, size, params);
        return Result.success(result);
    }

    @Operation(summary = "查询学生详情", description = "根据学生ID查询学生详细信息")
    @GetMapping("/{studentId}")
    public Result<Student> getStudentDetail(
            @Parameter(description = "学生ID", required = true) @PathVariable @NotBlank String studentId) {
        Student student = studentService.getStudentDetail(studentId);
        return Result.success(student);
    }

    @Operation(summary = "新增学生", description = "添加新的学生信息")
    @PostMapping
    public Result<Void> addStudent(@Valid @RequestBody Student student) {
        boolean success = studentService.addStudent(student);
        return success ? Result.success("学生添加成功") : Result.error("学生添加失败");
    }

    @Operation(summary = "新增学生", description = "添加新的学生信息")
    @PostMapping
    public Result<Void> addStudent(@Valid @RequestBody Student student) {
        boolean success = studentService.addStudent(student);
        return success ? Result.success("学生添加成功") : Result.error("学生添加失败");
    }

    @Operation(summary = "更新学生信息", description = "根据学生ID更新学生信息")
    @PutMapping("/{studentId}")
    public Result<Void> updateStudent(
            @Parameter(description = "学生ID", required = true) @PathVariable @NotBlank String studentId,
            @Valid @RequestBody Student student) {
        student.setStudentId(studentId);
        boolean success = studentService.updateStudent(student);
        return success ? Result.success("学生信息更新成功") : Result.error("学生信息更新失败");
    }

    @Operation(summary = "删除学生", description = "根据学生ID删除学生信息")
    @DeleteMapping("/{studentId}")
    public Result<Void> deleteStudent(
            @Parameter(description = "学生ID", required = true) @PathVariable @NotBlank String studentId) {
        boolean success = studentService.deleteStudent(studentId);
        return success ? Result.success("学生删除成功") : Result.error("学生删除失败");
    }

    @Operation(summary = "批量删除学生", description = "根据学生ID列表批量删除学生")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteStudents(
            @Parameter(description = "学生ID列表", required = true) @RequestBody @NotEmpty List<String> studentIds) {
        boolean success = studentService.batchDeleteStudents(studentIds);
        return success ? Result.success("批量删除成功") : Result.error("批量删除失败");
    }

    @Operation(summary = "根据班级查询学生", description = "根据班级ID查询该班级的所有学生")
    @GetMapping("/class/{classId}")
    public Result<List<Student>> getStudentsByClass(
            @Parameter(description = "班级ID", required = true) @PathVariable @NotBlank String classId) {
        List<Student> students = studentService.getStudentsByClassId(classId);
        return Result.success(students);
    }

    @Operation(summary = "根据身份证号查询学生", description = "根据身份证号查询学生信息")
    @GetMapping("/idcard/{idCard}")
    public Result<Student> getStudentByIdCard(
            @Parameter(description = "身份证号", required = true) @PathVariable @NotBlank String idCard) {
        Student student = studentService.getStudentByIdCard(idCard);
        return Result.success(student);
    }

    @Operation(summary = "学生转班", description = "将学生转移到新的班级")
    @PutMapping("/{studentId}/transfer")
    public Result<Void> transferClass(
            @Parameter(description = "学生ID", required = true) @PathVariable @NotBlank String studentId,
            @Parameter(description = "新班级ID", required = true) @RequestParam @NotBlank String newClassId) {
        boolean success = studentService.transferClass(studentId, newClassId);
        return success ? Result.success("转班成功") : Result.error("转班失败");
    }

    @Operation(summary = "批量转班", description = "批量将学生转移到新的班级")
    @PutMapping("/batch/transfer")
    public Result<Void> batchTransferClass(
            @Parameter(description = "学生ID列表", required = true) @RequestBody @NotEmpty List<String> studentIds,
            @Parameter(description = "新班级ID", required = true) @RequestParam @NotBlank String newClassId) {
        boolean success = studentService.batchTransferClass(studentIds, newClassId);
        return success ? Result.success("批量转班成功") : Result.error("批量转班失败");
    }

    @Operation(summary = "更新学生状态", description = "更新学生的状态信息")
    @PutMapping("/{studentId}/status")
    public Result<Void> updateStudentStatus(
            @Parameter(description = "学生ID", required = true) @PathVariable @NotBlank String studentId,
            @Parameter(description = "新状态", required = true) @RequestParam @NotBlank String status) {
        boolean success = studentService.updateStudentStatus(studentId, status);
        return success ? Result.success("状态更新成功") : Result.error("状态更新失败");
    }

    @Operation(summary = "批量更新学生状态", description = "批量更新学生的状态信息")
    @PutMapping("/batch/status")
    public Result<Void> batchUpdateStudentStatus(
            @Parameter(description = "学生ID列表", required = true) @RequestBody @NotEmpty List<String> studentIds,
            @Parameter(description = "新状态", required = true) @RequestParam @NotBlank String status) {
        boolean success = studentService.batchUpdateStudentStatus(studentIds, status);
        return success ? Result.success("批量状态更新成功") : Result.error("批量状态更新失败");
    }

    @Operation(summary = "学生统计-按班级", description = "统计各班级的学生数量")
    @GetMapping("/statistics/class")
    public Result<List<Map<String, Object>>> getStudentCountByClass() {
        List<Map<String, Object>> result = studentService.getStudentCountByClass();
        return Result.success(result);
    }

    @Operation(summary = "学生统计-按年级", description = "统计各年级的学生数量")
    @GetMapping("/statistics/grade")
    public Result<List<Map<String, Object>>> getStudentCountByGrade() {
        List<Map<String, Object>> result = studentService.getStudentCountByGrade();
        return Result.success(result);
    }

    @Operation(summary = "学生统计-按状态", description = "统计各状态的学生数量")
    @GetMapping("/statistics/status")
    public Result<List<Map<String, Object>>> getStudentCountByStatus() {
        List<Map<String, Object>> result = studentService.getStudentCountByStatus();
        return Result.success(result);
    }

    @Operation(summary = "根据监护人电话查询学生", description = "根据监护人电话查询相关学生")
    @GetMapping("/guardian/{guardianPhone}")
    public Result<List<Student>> getStudentsByGuardianPhone(
            @Parameter(description = "监护人电话", required = true) @PathVariable @NotBlank String guardianPhone) {
        List<Student> students = studentService.getStudentsByGuardianPhone(guardianPhone);
        return Result.success(students);
    }

    @Operation(summary = "查询即将毕业的学生", description = "查询指定年份即将毕业的学生")
    @GetMapping("/graduating")
    public Result<List<Student>> getGraduatingStudents(
            @Parameter(description = "毕业年份") @RequestParam(required = false) Integer graduationYear) {
        List<Student> students = studentService.getGraduatingStudents(graduationYear);
        return Result.success(students);
    }

    @Operation(summary = "查询新入学学生", description = "查询指定时间范围内新入学的学生")
    @GetMapping("/new-enrollment")
    public Result<List<Student>> getNewEnrollmentStudents(
            @Parameter(description = "开始日期", example = "2024-01-01") @RequestParam String startDate,
            @Parameter(description = "结束日期", example = "2024-12-31") @RequestParam String endDate) {
        List<Student> students = studentService.getNewEnrollmentStudents(startDate, endDate);
        return Result.success(students);
    }

    @Operation(summary = "查询未分班学生", description = "查询还未分配班级的学生")
    @GetMapping("/without-class")
    public Result<List<Student>> getStudentsWithoutClass() {
        List<Student> students = studentService.getStudentsWithoutClass();
        return Result.success(students);
    }

    @Operation(summary = "按年龄范围查询学生", description = "根据年龄范围查询学生")
    @GetMapping("/age-range")
    public Result<List<Student>> getStudentsByAgeRange(
            @Parameter(description = "最小年龄") @RequestParam Integer minAge,
            @Parameter(description = "最大年龄") @RequestParam Integer maxAge) {
        List<Student> students = studentService.getStudentsByAgeRange(minAge, maxAge);
        return Result.success(students);
    }

    @Operation(summary = "搜索学生", description = "根据关键词模糊搜索学生")
    @GetMapping("/search")
    public Result<List<Student>> searchStudents(
            @Parameter(description = "搜索关键词", required = true) @RequestParam @NotBlank String keyword) {
        List<Student> students = studentService.searchStudents(keyword);
        return Result.success(students);
    }

    @Operation(summary = "获取学生总数", description = "获取系统中学生的总数量")
    @GetMapping("/count/total")
    public Result<Long> getTotalStudentCount() {
        Long count = studentService.getTotalStudentCount();
        return Result.success(count);
    }

    @Operation(summary = "获取活跃学生数", description = "获取活跃状态学生的数量")
    @GetMapping("/count/active")
    public Result<Long> getActiveStudentCount() {
        Long count = studentService.getActiveStudentCount();
        return Result.success(count);
    }

    @Operation(summary = "导入学生数据", description = "批量导入学生信息")
    @PostMapping("/import")
    public Result<Map<String, Object>> importStudents(
            @Parameter(description = "学生信息列表", required = true) @RequestBody @NotEmpty List<Student> students) {
        Map<String, Object> result = studentService.importStudents(students);
        return Result.success("导入完成", result);
    }

    @Operation(summary = "导出学生数据", description = "根据条件导出学生信息")
    @GetMapping("/export")
    public Result<List<Student>> exportStudents(
            @Parameter(description = "班级ID") @RequestParam(required = false) String classId,
            @Parameter(description = "学生状态") @RequestParam(required = false) String status,
            @Parameter(description = "年级") @RequestParam(required = false) Integer gradeLevel) {
        
        Map<String, Object> params = Map.of(
            "classId", classId != null ? classId : "",
            "status", status != null ? status : "",
            "gradeLevel", gradeLevel != null ? gradeLevel : ""
        );
        
        List<Student> students = studentService.exportStudents(params);
        return Result.success(students);
    }

    @Operation(summary = "生成学生ID", description = "根据班级和入学年份生成学生ID")
    @GetMapping("/generate-id")
    public Result<String> generateStudentId(
            @Parameter(description = "班级ID") @RequestParam(required = false) String classId,
            @Parameter(description = "入学年份") @RequestParam(required = false) Integer enrollmentYear) {
        String studentId = studentService.generateStudentId(classId, enrollmentYear);
        return Result.success(studentId);
    }

    @Operation(summary = "验证学生信息", description = "验证学生信息的有效性")
    @PostMapping("/validate")
    public Result<Map<String, String>> validateStudent(
            @Parameter(description = "学生信息", required = true) @RequestBody Student student) {
        Map<String, String> errors = studentService.validateStudent(student);
        return Result.success(errors);
    }
}